package com.gome.ocean.service.task;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.InterruptableJob;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.quartz.UnableToInterruptJobException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

/**
 * 任务基础类
 * 
 * @author haqiaolong 2016年4月14日 上午10:14:59
 * @since 5.0.0
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public abstract class ScheduledJobTask extends QuartzJobBean implements InterruptableJob {

    protected static final Logger          LOG              = LoggerFactory.getLogger(ScheduledJobTask.class);

    protected volatile boolean             isJobInterrupted = false;
    private volatile Thread                thisThread;
    protected volatile JobExecutionContext context;

    @Override
    public void interrupt() throws UnableToInterruptJobException {
        isJobInterrupted = true;
        if (thisThread != null) {
            thisThread.interrupt();
        }
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        this.thisThread = Thread.currentThread();
        this.context = context;
        if (checkTask()) {
            initTask();
            if (!isJobInterrupted) {
                runTask();
            }
        }
    }

    public abstract boolean checkTask() throws JobExecutionException;

    public abstract void initTask() throws JobExecutionException;

    public abstract void runTask() throws JobExecutionException;

}
